package cn.kgc.crowdfundingadminspringboot3.service;

import cn.kgc.crowdfundingadminspringboot3.common.CrowdFundingUtils;
import cn.kgc.crowdfundingadminspringboot3.mapper.AdminMapper;
import cn.kgc.crowdfundingadminspringboot3.mapper.AuthMapper;
import cn.kgc.crowdfundingadminspringboot3.mapper.RoleMapper;
import cn.kgc.crowdfundingadminspringboot3.pojo.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class CrowdUserDetailsService implements UserDetailsService{

    @Resource
    AdminMapper adminMapper;

    @Resource
    RoleMapper roleMapper;

    @Resource
    AuthMapper authMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AdminExample example=new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andLoginacctEqualTo(s);
        List<Admin> admins = adminMapper.selectByExample(example);
        if(CrowdFundingUtils.collectionEffective(admins)){
            Admin admin = admins.get(0);
            //封装角色和权限的集合
            List<GrantedAuthority> authorities=new ArrayList<>();
            //获取角色
            List<Role> roleList = roleMapper.getAssignedRoleList(admin.getId());
            //获取角色编号，查询权限会用到
            List<Integer> roleIds=new ArrayList<>();
            //封装角色
            for (Role role : roleList) {
                String roleName="ROLE_"+role.getName();
                authorities.add(new SimpleGrantedAuthority(roleName));
                roleIds.add(role.getId());
            }
            //封装权限
            List<Auth> auths = authMapper.selectByRoleIds(roleIds);
            for (Auth auth : auths) {
                if (CrowdFundingUtils.stringEffective(auth.getName()) == false) {
                    continue;
                }
                authorities.add(new SimpleGrantedAuthority(auth.getName()));
            }
//            User user = new User(admin.getLoginacct(),admin.getUserpswd(),authorityList);
//            return user;
            SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);
            return securityAdmin;
        }else{
            return null;
        }
    }
}
